# Untitled - By: lenovo - Fri Sep 6 2024


# 引用库文件 #######################################################################################

import sensor
import image
import time
import network
import sys
import socket
from pyb import LED
from pyb import UART


# 全局变量 #########################################################################################

# 连接网络信息
SSID = "esp_test"
KEY = "xcz12345678"
# 服务端绑定信息
HOST = "192.168.22.1"
PORT = 8080

# 摄像头初始化
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.HQVGA)
sensor.skip_frames(time=2000)

# wlan对象初始化 sta模式
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(SSID, KEY)
# wlan对象初始化 ap模式
#wlan = network.WLAN(network.AP_IF)
#wlan.active(True)
#wlan.config(ssid=SSID, key=KEY, channel=2)
#print("AP mode started. SSID: {} IP: {}".format(SSID, wlan.ifconfig()[0]))

# 创建串口通信对象
uart = UART(3, 115200, bits=8, parity=None, stop=1)


# 函数部分 #########################################################################################

# 发送数据
def UART_SendErr(err):
    global uart
    sendarray = str(err[0]) + ' ' + str(err[1])
    uart.write(sendarray)
    print(sendarray)
    print('')


# 接收连接并发送图像
def video_send(client):
    img = sensor.snapshot()
    # 去畸变
    img.lens_corr(strength=1.8, zoom=1.0)
    img.draw_cross(img.width() // 2, img.height() // 2, size=10, thinkness=3)
    # 图片压缩
    cframe = img.compress(quality=20)
    jpeg = cframe.to_jpeg(copy=False)

    # 发送图片
    client.send(jpeg)
    end = "hello"
    client.send(end)
    print(jpeg.size())
    return client.recv(2)


# 代码执行部分 ######################################################################################

# 显示红灯并每秒连接一次网络直至连接成功
led = LED(1)
led.on()
while not wlan.isconnected():
    wlan.connect(SSID, KEY)
    time.sleep_ms(1000)
    print("wifi connect err")
led.off()

print("WiFi Connected ", wlan.ifconfig())

clock = time.clock()

while True:
    try:
        # 创建套接字
        videoclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#        videoclient.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
#        # 开启监听，一次仅可被一个头盔连接
#        videoserve.bind([HOST, PORT])
#        videoserve.listen(3)
        # 阻塞等待
        videoclient.setblocking(True)
        sockaddr = socket.getaddrinfo(HOST, PORT)[0][-1]
        # 执行任务
        # 等待连接头盔控制器连接并亮蓝灯
        led = LED(3)
        led.on()
        # 等待连接
        videoclient.connect(sockaddr)
        # 连接完成,关闭蓝色状态灯
        led.off()

        while True:
            clock.tick()
            print(video_send(videoclient))
            print(clock.fps())

    except OSError as e:
        videoclient.close()
        print('client except')
        continue
